import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:video_thumbnail/video_thumbnail.dart';

class VideoPlayerFirstPhoto extends StatefulWidget {
  final String videoUrl;

  final Function onPlayer;

  /// 图片中心的播放按钮对外
  /// 可以由外面传入，这样可以在这个位置做一些个性化，比如下载图标转圈圈等等
  final Widget centerWidget;

  VideoPlayerFirstPhoto({Key key, @required this.videoUrl, this.onPlayer, this.centerWidget}) : super(key: key);

  @override
  VideoPlayerFirstPhotoState createState() => VideoPlayerFirstPhotoState();
}

class VideoPlayerFirstPhotoState extends State<VideoPlayerFirstPhoto> with AutomaticKeepAliveClientMixin {
  Uint8List _utf8;

  bool _initialize = false;

  @override
  void initState() {
    this._getVideoThumbnailImage();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return (_initialize == true && _utf8 != null) ? _buildStackPlayerWidget() : Center(child: SpinKitCircle(color: Theme.of(context).primaryColor, size: 26.0));
  }

  Widget _buildStackPlayerWidget() {
    return GestureDetector(
      onTap: widget.onPlayer == null ? null : widget.onPlayer,
      child: Stack(
        children: [
          Container(child: Image.memory(this._utf8, fit: BoxFit.fill), width: double.infinity, height: double.infinity),
          _buildVideoItemPlayButtonWidget(),
        ],
      ),
    );
  }

  Widget _buildVideoItemPlayButtonWidget() {
    if (widget.centerWidget != null) return Container(width: double.infinity, height: double.infinity, alignment: Alignment.center, child: widget.centerWidget);
    return Container(width: double.infinity, height: double.infinity, child: Icon(Icons.play_circle, color: Colors.white, size: 40.0));
  }

  void _getVideoThumbnailImage() async {
    final uint8list = await VideoThumbnail.thumbnailData(
      video: _executeUriParse(widget.videoUrl),
      imageFormat: ImageFormat.PNG,
      maxWidth: 128,
      quality: 25,
    );
    setState(() {
      this._initialize = true;
      this._utf8 = uint8list;
    });
  }

  String _executeUriParse(String object) {
    Uri videoUrl = Uri.parse(object);
    return videoUrl.toString();
  }

  @override
  bool get wantKeepAlive => true;
}
